<script setup lang="ts">
/**
 * @prop {string} icon - 双向绑定, 当前选择的icon
 *
 * @event update:icon - 双向绑定, 当前选择的icon
 */
import { ElButton, ElIcon, ElInput, ElPopover } from 'element-plus';
import { h } from 'vue';
import { computed } from 'vue';

import Icon from './Icon.vue';

const props = defineProps<{
  icon?: string;
  iconList: {
    css_prefix_text: string;
    glyphs: { font_class: string; icon_id: any }[];
  };
}>();
const emits = defineEmits<{
  (e: 'update:icon', value?: string): void;
}>();
const icon = computed({
  get: () => {
    return props.icon;
  },
  set: (val) => {
    emits('update:icon', val);
  },
});
const setIcon = (iconClass: string) => {
  icon.value = iconClass;
};
</script>

<template>
  <el-input v-model="icon" placeholder="请选择图标">
    <template #append>
      <el-popover
        placement="bottom-end"
        :hide-after="0"
        trigger="click"
        popper-style="width: 312px; height: 300px; overflow-y: auto; overflow-x: hidden;"
      >
        <template #reference>
          <el-button :icon="() => h(Icon, { icon: icon ? icon : 'icon-setting' })" />
        </template>
        <div class="icon-box">
          <el-icon
            v-for="item in iconList.glyphs"
            :key="item.icon_id"
            :class="iconList.css_prefix_text + item.font_class === icon ? 'icon-selected icon-item' : 'icon-item'"
            @click="setIcon(iconList.css_prefix_text + item.font_class)"
          >
            <Icon :icon="iconList.css_prefix_text + item.font_class" />
          </el-icon>
        </div>
      </el-popover>
    </template>
  </el-input>
</template>

<style lang="scss" scoped>
.icon-box {
  display: flex;
  flex-wrap: wrap;
  overflow-y: auto;
  .icon-item {
    width: 40px;
    height: 40px;
    font-size: 30px;
    line-height: 40px;
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.5s;
    &:hover {
      transition: background-color 0.05s;
      background-color: var(--el-fill-color-light);
    }
  }
  .icon-selected {
    color: var(--el-color-primary);
  }
}
</style>
